package com.cos.lession59.services.impl;

import com.cos.lession59.dao.SysRoleMapper;
import com.cos.lession59.dao.SysUserMapper;
import com.cos.lession59.entity.SysRole;
import com.cos.lession59.entity.SysUser;
import com.cos.lession59.services.SysUserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: COS
 * @time: 2022/3/14 9:39
 * @description:
 */
@Service
public class SysUserServicesImpl implements SysUserServices {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1 使用用户名 到数据查询用户的数据
        SysUser user = userMapper.getSysUserByUsername(username);
        //2 当用户存在的时候
        if (user != null) {
            //3 获取用户拥有的权限信息
            List<SysRole> userRoles = roleMapper.getSysRoleByUserId(user.getId());
            //4 创建list SimpleGrantedAuthority 的集合用于保存用户拥有的权限
            List<SimpleGrantedAuthority> roles = new ArrayList<>();
            //5 把用户权限的名字转存到SimpleGrantedAuthority集合中
            for (SysRole userRole : userRoles) {
                roles.add(new SimpleGrantedAuthority(userRole.getName()));
            }
            //6 创建 new User() 通过他用户名密码权限集合创建出 UserDetail对象
            UserDetails userDetails = new User(user.getUsername(),user.getPassword(),roles);
            // 返回给 springSecurity
            return userDetails;
        }
        return null;
    }

    @Override
    public SysUser getSysUserByUsername(String username) {
        if (username!=null&&username.trim().length()>0) {
            SysUser user = userMapper.getSysUserByUsername(username);
            if (user != null) {
                return user;
            }
        }
        return null;
    }
}
